#ifndef NET_ACCEPTOR_H
#define NET_ACCEPTOR_H

#include "Socket.h"
#include "utility/Noncopyable.h"

#include <functional>
#include <memory>
#include <optional>

class Sockaddr;
class IOchannel;
class Eventloop;

/// @class owned by independent IO thread
class Acceptor final
{
public:
    using NewConnectionCallback = std::function<void(std::unique_ptr<Socket> &&, const Sockaddr &)>;

    /// @param addr bind to @c addr
    Acceptor(Eventloop &loop, const Sockaddr &addr, bool resusePort);
    ~Acceptor();

    bool is_listening() const { return _listening; }
    void set_new_connection_callback(const NewConnectionCallback &callback);

    void listen();

private:
    NONCOPYABLE(Acceptor);

    void _accept_error();
    void _read_callback();

    std::optional<NewConnectionCallback> _newConnectionCallback;
    const Eventloop &_loop;
    std::unique_ptr<IOchannel> _channel;
    const Socket _socket;
    int _fdReservered;
    bool _listening;

};



#endif